//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"bytes"
	"strings"

	"atomgit.com/openlinksaas/search-proxy/core"
	"github.com/antchfx/htmlquery"
)

type GithubParser struct{}

func (parser *GithubParser) MatchUrl(url string) bool {
	return strings.HasPrefix(url, "https://github.com/search")
}

func (parser *GithubParser) Parse(url string) ([]*core.SearchEntry, error) {
	body, err := GetPage(url)
	if err != nil {
		return nil, err
	}

	doc, err := htmlquery.Parse(bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}

	retList := []*core.SearchEntry{}
	prjElList := htmlquery.Find(doc, "//div[@data-testid='results-list']/div")
	for _, prjEl := range prjElList {
		summary := ""
		descElList := htmlquery.Find(prjEl, "//span[contains(@class,'search-match')]")
		if len(descElList) > 1 {
			summary = htmlquery.InnerText(descElList[1])
		}
		linkEl := htmlquery.FindOne(prjEl, "//h3//div[contains(@class,'search-title')]/a")
		if linkEl != nil {
			retList = append(retList, &core.SearchEntry{
				Title:   htmlquery.InnerText(linkEl),
				Url:     "https://github.com" + htmlquery.SelectAttr(linkEl, "href"),
				Summary: summary,
			})
		}
	}
	return retList, nil
}
